package com.example.cinema;

import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;

import com.example.cinema.bindingdata.Advert;
import com.example.cinema.bindingdata.StartData;
import com.example.cinema.database.AppDataBase;
import com.example.cinema.database.DataBaseMethod;
import com.example.cinema.databinding.ActivityStartBinding;
import com.example.cinema.request.RequestData;
import com.example.cinema.request.RequestInitData;
import com.example.cinema.request.RequestSend;
import com.example.cinema.toolclass.AmbientInspect;
import com.example.cinema.toolclass.SvgaAnim;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import pub.devrel.easypermissions.EasyPermissions;

public class StartActivity extends AppCompatActivity implements EasyPermissions.PermissionCallbacks {
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        Toast.makeText(this, "相关权限获取成功", Toast.LENGTH_LONG).show();
        //已获取到了权限
        try {
            Log.i("AAA", "执行完毕");
            init();
            Log.i("AAA", "执行完毕");
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        Toast.makeText(this, "相关权限获取失败", Toast.LENGTH_LONG).show();
    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {
        Log.i("PPP", hasCapture + "");
    }


    //获取权限
    private void ReqPermissions() {
        if (EasyPermissions.hasPermissions(this, RequestAuthority.permissions)) {
            try {
                init();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            EasyPermissions.requestPermissions(this, "需要部分权限才能正常使用", 1, RequestAuthority.permissions);
        }

    }


    private ActivityStartBinding ASB;
    private StartData startData;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ASB = DataBindingUtil.setContentView(this, R.layout.activity_start);
        Log.i("DDDD", "s1");
        startData = new StartData();
        startData.surplus.set(0);
        startData.surplusmax.set(15);
        startData.syrptxt.set("初始化网络");
        ASB.setStartdata(startData);
        try {
            ApplicationInfo info = getPackageManager().getApplicationInfo(getPackageName(), PackageManager.GET_META_DATA);

        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        Log.i("DDDD", "s1");
        initfont();
        ReqPermissions();
        initlistener();
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) {
            View view = getWindow().getDecorView();
            view.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            View view = getWindow().getDecorView();
            int UIOP = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_FULLSCREEN;
            view.setSystemUiVisibility(UIOP);
        }
    }

    private void initlistener() {
        ASB.close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setAction("maininlet");
                startActivity(intent);
            }
        });
        ASB.advertimg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Uri uri = Uri.parse(url);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
            }
        });
    }


    private void initfont() {
        Typeface typeface = Typeface.createFromAsset(getAssets(), "fonts/hanyishu.TTF");
        try {
            Field field = Typeface.class.getDeclaredField("MONOSPACE");
            field.setAccessible(true);
            field.set(null, typeface);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }


    String url = null;
    int pross = 1;
    Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1000) {
                ASB.close.setVisibility(View.VISIBLE);
                return;
            }

            if (msg.what == 1003) {
                JSONObject JO = (JSONObject) msg.obj;
                try {
                    startData.bagimage.set(JO.getString("adverurl"));
                    url = JO.getString("adverskip");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            pross++;
            Log.i("KKKD", pross + "");
            startData.surplus.set(pross);
            int pro = ASB.seek.getProgress();
            Log.i("HHHH", "进度" + pro);
            Log.i("HHHH", "总量" + ASB.seek.getMax());
            int max = ASB.seek.getMax();
            if (pro >= max) {
                ASB.advert.setVisibility(View.VISIBLE);
                Log.i("HHHH", "初始化成功");
                skip();
            }
        }
    };

    private void skip() {
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                handler.sendEmptyMessage(1000);
            }
        }, 5000);

    }

    //开始请求初始化数据
    AmbientInspect Ai;
    RequestInitData reqdata;

    private void init() throws JSONException {
        //检测是否模拟器抓包工具
        Ai = new AmbientInspect(getApplicationContext());
        reqdata = new RequestInitData(getApplicationContext());
        StartInit();
        pross++;
    }

    //启动初始化
    private void StartInit() {
        Toast.makeText(this, Ai.result + "", Toast.LENGTH_LONG).show();
        System.out.println(Ai.result);
        if (Ai.result < 6) {
            Toast.makeText(this, "暂不支持模拟器", Toast.LENGTH_LONG).show();
//            return;
        }
        new Thread() {
            @Override
            public void run() {
                StartInita();
            }
        }.start();
        Log.i("EEER", "检测模拟器");
        handler.sendEmptyMessage(1001);
    }

    //检测是否黑名单用户
    private void StartInita() {

        String id = Ai.GetImei();
        boolean x = reqdata.BlackCheck(id);
        if (x) {
            Log.i("EEER", "检测黑名单");
            handler.sendEmptyMessage(1002);
            StartInitb();
        }
    }

    //获取启动页广告
    private void StartInitb() {


        JSONArray jo = reqdata.GetAdvert();
        if (jo == null) {
            Log.i("KKKK", "空的");
            return;
        }
        Log.i("KKKK", jo.toString());
        Message msg = new Message();
        try {
            msg.obj = jo.getJSONObject(0);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Log.i("EEER", "启动页广告");
        msg.what = 1003;
        handler.sendMessage(msg);
        StartInitC();
    }

    //获取海报
    private void StartInitC() {
        Log.i("JJJJJS","-----------------------------------");
        JSONArray ja = reqdata.GetPoster();
        if (ja != null) {
            AppDataBase dataBase = new AppDataBase(getApplicationContext(), "poster", null, 2);

            SQLiteDatabase sqldata = dataBase.getWritableDatabase();
            sqldata.delete("poster", null, null);
            for (int i = 0; i < ja.length(); i++) {
                String img = null;
                String urls = null;
                String type = null;
                String news = null;
                try {
                    JSONObject jo = ja.getJSONObject(i);
                    img = jo.getString("posterimg");

                    if (img == null) {
                        img = "1111";
                    }
                    Log.i("KJJJ", img);
                    urls = jo.getString("posterurl");

                    if (urls == null) {
                        urls = "1111";
                    }
                    Log.i("KJJJ", urls);
                    type = jo.getString("types");

                    if (type == null) {
                        type = "1111";
                    }
                    Log.i("KJJJ", type);
                    if(!jo.isNull("news")){
                        news = jo.getString("news");

                        if (news == null) {
                            news = "1111";
                        }
                    }

                    Log.i("KJJJ", "news:"+news);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                ContentValues values = new ContentValues();
                values.put("image", img);
                values.put("urls", urls);
                values.put("types", type);
                values.put("apskk", news);
                long s = sqldata.insert("poster", null, values);
                Log.i("KJJJ", s + "海报数据");
            }

            handler.sendEmptyMessage(1004);
            Log.i("EEER", "获取海报");
            Log.i("JJJJJS","-----------------------------------");
            StartInitD();

        }
    }

    //获取分类
    private void StartInitD() {

        JSONArray array = reqdata.GetType();
        if (array != null) {
            AppDataBase dataBase = new AppDataBase(getApplicationContext(), "videotype", null, 2);
            SQLiteDatabase sqldata1 = dataBase.getWritableDatabase();
            sqldata1.delete("videotype", null, null);
            for (int i = 0; i < array.length(); i++) {
                try {
                    JSONObject Jo = array.getJSONObject(i);
                    String id = Jo.getString("typeid");
                    String nam = Jo.getString("typename");
                    String tid = Jo.getString("typenume");

                    ContentValues values = new ContentValues();
                    values.put("typeid", id);
                    values.put("typename", nam);
                    values.put("typenume", tid);

                    long ss = sqldata1.insert("videotype", null, values);

                    Log.i("SSSS", ss + "插入结果");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
        StartE();
        handler.sendEmptyMessage(1005);
        Log.i("EEER", "获取分类");
    }

    //获取短视频数据
    private void StartE() {
        JSONArray array = reqdata.GetShortData();
//        Log.i("SSSS", array.length() + "");
        if (array != null) {
            AppDataBase dataBase = new AppDataBase(getApplicationContext(), "videom3u8", null, 2);

            SQLiteDatabase sqldata2 = dataBase.getWritableDatabase();
            sqldata2.delete("videom3u8", null, null);
            for (int i = 0; i < array.length(); i++) {
                Log.i("SSSS", "开始遍历");
                try {
                    JSONObject Jo = array.getJSONObject(i);

                    Log.i("SSSS", "执行插入操作01");
                    ContentValues values = new ContentValues();
                    values.put("videosid", Jo.getString("videosid"));
                    values.put("videoname", Jo.getString("videoname"));
                    values.put("videotype", Jo.getString("videotype"));
                    values.put("videotime", Jo.getString("videotime"));
                    values.put("videobrief", Jo.getString("videobrief"));
                    values.put("videopath", Jo.getString("videopath"));
                    values.put("videogif", Jo.getString("videogif"));
                    values.put("videoimg", Jo.getString("videoimg"));
                    values.put("videotag", Jo.getString("videotag"));
                    values.put("videocover", Jo.getString("videocover"));
                    values.put("videouser", Jo.getString("videouser"));
                    values.put("videousid", Jo.getString("videousid"));
                    values.put("videopart", Jo.getString("videopart"));
                    values.put("videolove", Jo.getString("videolove"));
                    values.put("videouimg", Jo.getString("videouimg"));
                    long ss = sqldata2.insert("videom3u8", null, values);
                    Log.i("SSSS", ss + "短视频");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            handler.sendEmptyMessage(1005);

        }
        handler.sendEmptyMessage(1006);
        Log.i("EEER", "短视频数据");
        GetNotice();
    }

    //获取公告
    private void GetNotice() {
        Log.i("EEER", "获取公告");
        JSONObject notice = reqdata.GetNotice();
        if (notice != null) {

            AppDataBase dataBase = new AppDataBase(getApplicationContext(), "notice", null, 2);
            SQLiteDatabase sqldata = dataBase.getWritableDatabase();
            sqldata.delete("notice", null, null);
            ContentValues values = new ContentValues();
            try {
                values.put("noticetitle", notice.getString("noticetitle"));
                values.put("noticetexts", notice.getString("noticetexts"));
                long ss = sqldata.insert("notice", null, values);
                Log.i("SSSS", "成功插入" + ss);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        handler.sendEmptyMessage(1007);
        Log.i("EEER", "短视频数据");
        GetLive();
    }

    //获取直播数据
    private void GetLive() {
        AppDataBase dataBase = new AppDataBase(getApplicationContext(), "livertmp", null, 2);
        SQLiteDatabase sqldata = dataBase.getWritableDatabase();
        sqldata.delete("livertmp", null, null);
        JSONArray live = reqdata.GetLiveData();
        if (live != null) {
            int len = live.length();
            for (int u = 0; u < len; u++) {
                ContentValues values = new ContentValues();
                try {
                    JSONObject livejo = live.getJSONObject(u);
                    values.put("livesid", livejo.getString("livesid"));
                    values.put("livepath", livejo.getString("livepath"));
                    values.put("livetype", livejo.getString("livetype"));
                    values.put("livename", livejo.getString("livename"));
                    values.put("livestate", livejo.getString("livestate"));
                    values.put("livecover", livejo.getString("livecover"));
                    values.put("livetext", livejo.getString("livetext"));
                    values.put("livetag", livejo.getString("livetag"));
                    values.put("liverelay", livejo.getString("liverelay"));
                    sqldata.insert("livertmp", null, values);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
        handler.sendEmptyMessage(1007);
        Log.i("EEER", "直播数据");
        GetSpread();
    }

    //获取推广地址
    private UserAttribute attribute;
    private void GetSpread() {
        Log.i("LLLS", "获取推广地址");
        attribute = (UserAttribute) getApplication();
        JSONObject JO = reqdata.GetDowUrl();
        if (JO != null) {
            AppDataBase dataBase = new AppDataBase(getApplicationContext(), "dowtable", null, 2);
            SQLiteDatabase sqldatabase = dataBase.getWritableDatabase();
            ContentValues values = new ContentValues();
            try {
                String url = JO.getString("dowurl");
                values.put("url", url);
                String img = JO.getString("dowbag");
                values.put("img", img);
                attribute.setDowurl(url);
                attribute.setDowbag(img);
                sqldatabase.insert("dowtable", null, values);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        GetVip();
        handler.sendEmptyMessage(1008);
        Log.i("EEER", "获取推广地址");
    }

    //获取VIP充值数据
    private void GetVip() {
        Log.i("LLLS", "获取VIP充值数据");
        AppDataBase dataBase = new AppDataBase(getApplicationContext(), "vipmoney", null, 2);
        SQLiteDatabase sqldata = dataBase.getWritableDatabase();
        JSONArray array = reqdata.GetMoney();
        Log.i("eeee", array.length() + "数量");
        try {
            Log.i("eeee", array.getJSONObject(0).getString("viptitle") + "数量");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        for (int i = 0; i < array.length(); i++) {
            ContentValues values = new ContentValues();
            try {
                JSONObject jo = array.getJSONObject(i);
                String title = jo.getString("viptitle");
                double money = jo.getDouble("vipmone");
                String masg = jo.getString("vipmasg");
                values.put("viptitle", title);
                Log.i("HHH", title);
                values.put("vipmoney", money);
                Log.i("HHH", money + "");
                values.put("vipmasg", masg);
                Log.i("HHH", masg);
                sqldata.insert("vipmoney", null, values);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        Log.i("EEER", "VIP充值数据");
        handler.sendEmptyMessage(1009);
        GetAdverData();
    }

    //获取模块广告
    private void GetAdverData() {

        Log.i("LLLS", "获取模块广告");
        List<Advert> adverts = reqdata.GetAdverXq();
        AppDataBase dataBase = new AppDataBase(getApplicationContext(), "adverdata", null, 2);
        SQLiteDatabase sqLiteDatabase = dataBase.getWritableDatabase();
        sqLiteDatabase.delete("adverdata", null, null);
        for (int i = 0; i < adverts.size(); i++) {
            ContentValues values = new ContentValues();
            Advert advert = adverts.get(i);
            values.put("adverurl", advert.adverurl);
            values.put("adverskip", advert.adverskip);
            long bb = sqLiteDatabase.insert("adverdata", null, values);
            Log.i("HHHH", "结果" + bb);
        }
        Log.i("EEER", "获取模块广告");
        handler.sendEmptyMessage(10010);
        GetPlayAdverData();
    }

    //获取播放广告
    private void GetPlayAdverData() {
        Log.i("LLLS", "获取播放广告");
        List<Advert> adverts = reqdata.GetAdverPlay();
        AppDataBase dataBase = new AppDataBase(getApplicationContext(), "adverdatas", null, 2);
        SQLiteDatabase sqLiteDatabase = dataBase.getWritableDatabase();
        sqLiteDatabase.delete("adverdatas", null, null);
        for (int i = 0; i < adverts.size(); i++) {
            ContentValues values = new ContentValues();
            Advert advert = adverts.get(i);
            values.put("adverurl", advert.adverurl);
            values.put("adverskip", advert.adverskip);
            long bb = sqLiteDatabase.insert("adverdatas", null, values);
            Log.i("HHHH", "结果" + bb);
        }
        Log.i("EEER", "获取播放广告");
        handler.sendEmptyMessage(10011);
        GetAppMode();
    }

    //获取APP配置
    private void GetAppMode() {
        Log.i("EEER", "获取APP配置");
        reqdata.GetAppConfig(attribute);
        handler.sendEmptyMessage(10012);
        Getdownload();
    }


    //获取应用下载地址
    private void Getdownload() {
        Log.i("EEER", "获取应用下载地址");
        new RequestData(getApplicationContext()).Getdownload(attribute);
        handler.sendEmptyMessage(10013);
        UserSign();
    }


    //用户登录
    private void UserSign() {
        TelephonyManager manager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        String id = manager.getDeviceId();
        DataBaseMethod baseMethod = new DataBaseMethod(getApplicationContext(), "userinfo");
        Map<String, Object> map = baseMethod.GetUserData();
        if (map.get("nam") != null && map.get("psw") != null) {
            Log.i("AAAQQ", map.get("nam").toString());
            Log.i("AAAQQ", map.get("psw").toString());
            new RequestSend(getApplicationContext()).UserLong(map.get("nam").toString(), map.get("psw").toString(), attribute, id);
        }
        Log.i("EEER", "用户登录");
        handler.sendEmptyMessage(10014);
        GetQQtext();
    }


    //获取客服QQ
    private void GetQQtext() {
        Log.i("EEER", "获取客服QQ");
        RequestData requestData = new RequestData(getApplicationContext());
        requestData.GetQQ(attribute);
        handler.sendEmptyMessage(10015);
    }

}
